/* 用户状态通用方法 */
import util from '@/common/util.js'

/**
 * 获取授权 code
 */
const getLoginCode = (successFun) => {
	uni.login({
		success(res) {
			successFun(res)
		}
	})
}
/**
 * 静默获取用户信息
 */
const getUserInfo = () => {
	return new Promise((resolve, reject) => {
		uni.getUserInfo({
			lang: 'zh_CN',
			success(res) {
				resolve(res)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

/**
 * 检查是否存在 token 和登录标记 isLogin
 */
const checkLogin = () => {
	let token = getApp().globalData.token ? true : false
	let isLogin = getApp().globalData.isLogin
	if (token && isLogin) {
		// TODO what this mean?
		let newTime = Math.round(new Date() / 1000)
		if (getApp().globalData.expiredTime < newTime) return false
	}
	return token && isLogin
}
/**
 * 检查用户登录状态
 */
const checkLoginStatus = () => {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success(res) {
				if (!res.authSetting['scope.userInfo']) {
					// 未授权过，直接触发 catch()
					return reject({
						authSetting: false
					})
				} else {
					uni.getStorage({
						key: 'cache_key',
						success(res) {
							/* 已经登录的 */
							if (checkLogin()) {
								return resolve({
									userInfo: getApp().globalData.userInfo,
									isLogin: true
								})
							} else {
								/* 登录时间已经失效 */
								getUserInfo().then(userInfo => {
									userInfo.cache_key = res.data
									return resolve({
										userInfo: userInfo,
										isLogin: false
									})
								}).catch(err => {
									return reject(err)
								})
							}
						},
						fail() {
							// TODO what's mean this? callback the result with function arg ?
							/* 没有 cache_key 值则获取 code 重新发起登录 */
							getLoginCode((code) => {
								getUserInfo().then(userInfo => {
									userInfo.code = code
									return resolve({
										userInfo: userInfo,
										isLogin: false
									})
								}).catch(err => {
									return reject(err)
								})
							})
						}
					})
				}
			},
			fail(err) {
				return reject(err)
			}
		})
	})
}
/**
 * 导入微信地址
 */
const importWechatAddress = () => {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: 'scope.address',
			success: (res) => {
				uni.chooseAddress({
					success: (res) => {
						let wxAddress = {
							province: res.provinceName,
							city: res.cityName,
							district: res.countyName
						}
						let data = {
							address: wxAddress,
							real_name: res.userName,
							phone: res.telNumber,
							post_code: res.postalCode,
							detail: res.detailInfo,
							is_default: 1,
							id: 0
						}
						return resolve(data)
					},
					fail: (err) => {
						if (err.errMsg == 'chooseAddress:cancel') {
							util.Toast({ title: '取消选择' })
						}
					}
				})
			},
			fail: (err) => {
				uni.showModal({
					title: '提示',
					content: '您已拒绝导入微信地址，是否重新授权？',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting({
								success: (res) => {
									console.log(res.authSetting);
								}
							})
						} else if (res.cancel) {
							util.Toast({ title: '已取消' })
						}
					}
				})
			}
		})
	})
}

export default {
	getLoginCode,
	getUserInfo,
	checkLogin,
	checkLoginStatus,
	importWechatAddress
}